package com.test.springboot3.springboot3testdemo1.config;

import com.test.springboot3.springboot3testdemo1.schedule.QuartzSimpleTask;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.quartz.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/8/6-上午9:40
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@RequiredArgsConstructor
@Configuration
public class QuartzTaskConfig {
  public static final String SIMPLE_TASK_NAME = "simple-task";
  private final SchedulerFactoryBean schedulerFactoryBean;

  @PostConstruct
  public void init() throws SchedulerException {
    final Scheduler scheduler = schedulerFactoryBean.getScheduler();
    if (!scheduler.checkExists(JobKey.jobKey(SIMPLE_TASK_NAME))) {
      scheduler.scheduleJob(simpleQuartzTask(), simpleTaskTrigger());
    }
  }

  // @Bean
  public JobDetail simpleQuartzTask() {
    return JobBuilder.newJob(QuartzSimpleTask.class)
        .withIdentity("simpleTask")
        .withDescription("simple task")
        .storeDurably()
        .build();
  }

  // @Bean
  public Trigger simpleTaskTrigger() {
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/3 * * * * ? *");
    return TriggerBuilder.newTrigger()
        .withIdentity("simpleTaskTrigger")
        .forJob(simpleQuartzTask())
        .withSchedule(scheduleBuilder)
        .build();
  }
}
